// packageI/groupWork/groupWorkMy/groupWorkMy.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [{
      title: "正在拼团",
      id: 0
    },
    {
      title: "拼团成功",
      id: 1
    },
    {
      title: "拼团失败",
      id: 2
    }
    ],
    networkLoading: false,
    activeName: 0,
    dataList: [],
    loading: false,
    isLoadMore: true,

    //sku 规格弹窗data ====
    optionsId: 0,
    popupSpecs: false,
    goods: {},
    specs: [],
    options: [],
    // 拼团
    groupLevel: [],
    level_id: 0,
    activity_option_id: "", //团规格属性价格ID主键,下单需要
    alliance_detail_id: "", //团详情ID（拼团列表数据ID）,下单需要
    groupModel: "", //选择的拼团层级
    special_options: "", //层级和规格的组合
    selectGroupInfo: {}, //拼团层级列表
    imgPath: app.globalData.imgPath,
    //sku 规格弹窗data ======end
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.groupModel = 0;
    this.data.dataList = [];
    this.getData(true);
  },
  buyClicked(e) {
    console.log(e);
    let _data = {
      goodsId: this.data.goods.id,
      optionsId: e.detail.optionsId,
      total: 1,
      tag: "group-work",
      alliance_detail_id: this.data.alliance_detail_id,
      activity_option_id: this.data.activity_option_id
    };
    let url = "/packageD/buy/myOrder_v2/myOrder_v2?tag=groupWork";
    wx.navigateTo({
      url: url + "&goodsId=" + _data.goodsId + "&optionsId=" + _data.optionsId + "&total=1&alliance_detail_id=" + _data.alliance_detail_id + "&activity_option_id=" + _data.activity_option_id,
    });
  },
  getGoods(e) {
    let {
      activityid,
      specid,
      id
    } = e.currentTarget.dataset;
    this.data.alliance_detail_id = id;
    app._postNetWork({
      url: app.getNetAddresss("plugin.group-work.frontend.modules.goods.controllers.detail.index"),
      data: {
        record_id: activityid
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result != 1) return app.tips(res.msg);
        let goods = {};
        goods['id'] = res.data.goods_id;
        goods['has_option'] = res.data.goods_info.has_option;
        goods['thumb'] = res.data.goods_info.thumb;
        goods['unit'] = res.data.goods_info.sku;

        let groupLevel = res.data.specs.filter(function (v) {
          if (v.id == specid) {
            goods['price'] = v.min_price;
            return v;
          }
        }); //过滤层级，只显示之前开团参团支付的层级
        this.setData({
          goods: goods,
          specs: res.data.goods_info.has_many_specs,
          options: res.data.goods_info.has_many_options,
          groupModel: specid,
          groupLevel: groupLevel,
          special_options: res.data.special_options,

        });
        this.setData({
          popupSpecs: true
        });
        if (this.data.goods.has_option == 0) this.setGroupInfo(0);
      }
    });
  },
  skuSelected(e) {
    if (e) this.data.optionsId = e.detail;
    this.setGroupInfo(this.data.optionsId); //设置选择后规格对应的层级 过滤数据
  },
  //设置拼团层级的选择状态 过滤数据
  setGroupInfo(_id) {
    for (let i = 0; i < this.data.special_options.length; i++) {
      let _optionSpecs = this.data.special_options[i].option_id;
      //判断是否包含
      if (_optionSpecs == this.data.optionsId) {
        this.data.selectGroupInfo = this.data.special_options[i].activity_options;
        this.selectComponent('#yzSpecs').setData({
          popStock: this.data.special_options[i].stock //当前组合的库存
        });
        this.selectGroup(this.data.groupModel);
        return;
      }
    }
  },

  //选择拼团层级
  selectGroup(_level_id) {
    this.data.groupModel = _level_id;
    let selectGroupLever = "";
    if (_level_id) {
      if (this.data.goods.has_option == 1) {
        //有规格
        if (!this.data.optionsId) {
          app.tips("请选择商品规格！");
          this.data.groupModel = "";
        } else {
          selectGroupLever = this.data.selectGroupInfo.filter(function (v) {
            if (v.spec_id == _level_id) {
              return v.price;
            }
          });
          this.selectComponent('#yzSpecs').setData({
            popPrice: selectGroupLever[0].price
          });
          this.data.activity_option_id = selectGroupLever[0].id;
        }
      } else {
        //无规格
        this.data.selectGroupInfo = this.data.special_options[0].activity_options;
        selectGroupLever = this.data.selectGroupInfo.filter(function (v) {
          if (v.spec_id == _level_id) {
            return v.price;
          }
        });
        this.selectComponent('#yzSpecs').setData({
          popPrice: selectGroupLever[0].price
        });
        this.data.activity_option_id = selectGroupLever[0].id;
      }
    }
  },
  getTab(e) {
    this.setData({
      activeName: e.detail.name
    });
    this.getData(false);
  },
  getData(tag) {
    let status = ["1", "2", "-1"];
    let index = this.data.activeName;
    if (!tag && this.data.dataList[index].list.length > 0) {
      return;
    }
    this.setData({
      networkLoading: false
    });
    app._postNetWork({
      url: app.getNetAddresss("plugin.group-work.frontend.modules.alliance.controllers.records.index"),
      data: {
        status: status[index]
      },
      success: (resdata) => {
        this.setData({
          networkLoading: true
        });
        var res = resdata.data;
        if (res.result != 1) return app.tips(res.msg);
        let dataList = this.data.dataList;
        if (tag) {
          this.data.tabs.forEach((val, index) => {
            dataList.push({
              isLoadMore: true,
              page: 1,
              total_page: 0,
              list: []
            });
          });
          this.setData({
            dataList
          });
        }
        let list = res.data.page_list.data;
        for (let i = 0; i < list.length; i++) {
          list[i].timeDifference = app.getTimeDifference(list[i].remain_time);
        }
        this.setData({
          ['dataList[' + index + '].list']: list,
          ['dataList[' + index + '].total_page']: res.data.page_list.last_page,
          ['dataList[' + index + '].isLoadMore']: res.data.page_list.last_page == 1 ? false : true
        });
      }
    });
  },
  getMore() {
    let index = this.data.activeName;
    if (this.data.dataList[index].isLoadMore) {
      return; //防止重复触发
    }
    if (this.data.dataList[index].page >= this.data.dataList[index].total_page) {
      return;
    }
    this.data.dataList[index].isLoadMore = true;
    this.data.dataList[index].page += 1;
    let status = ["1", "2", "-1"];
    app._postNetWork({
      url: app.getNetAddresss("plugin.group-work.frontend.modules.alliance.controllers.records.index"),
      data: {
        status: status[index],
        page: this.data.dataList[index].page
      },
      success: (resdata) => {
        var res = resdata.data;
        this.data.dataList[index].isLoadMore = false;
        if (res.result != 1) {
          return app.tips(res.msg);
        } else {
          let list = res.data.page_list.data;
          for (let i = 0; i < list.length; i++) {
            list[i].timeDifference = app.getTimeDifference(list[i].remain_time);
          }
          this.setData({
            ['dataList[' + index + '].list']: this.data.dataList[index].list.concat(list),
          });
        }
      }
    });
  },
  gotoDetail(e) {
    let {
      allianceid,
      id
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/packageI/groupWork/groupWorkDetail/groupWorkDetail?allianceid=' + allianceid + "&id=" + id
    });
  },
  toOrder(e) {
    let {
      orderid
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/packageA/member/orderdetail/orderdetail?order_id=' + orderid + "&orderType=groupWork"
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getMore();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
});